package com.one2manycall.controller;

import com.one2manycall.service.UserOnlineManageServiceI;
import com.one2manycall.service.UserServiceI;
import com.one2manycall.service.websocket.UserRegistry;
import com.one2manycall.utils.JWTUtils;
import com.one2manycall.vo.LoginResponse;
import com.one2manycall.vo.User;
import com.one2manycall.vo.UserSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.ConcurrentMap;

/**
 * 登录相关的业务
 */
@Controller
@RequestMapping("/LoginController")
public class LoginController {
    @Autowired
    private UserRegistry userRegistry;


    @Autowired
    private UserServiceI userService;


    @Autowired
    private UserOnlineManageServiceI userOnlineManageServiceI;



    //// 页面部分 开始  /////////////////////////////////////
    @GetMapping("/toLogin")
    public String listRoles() {
        // 跳转登录页面
        return "html/user/login";
    }



    @PostMapping("/login")
    @ResponseBody
    public LoginResponse login(@RequestBody User loginRequest) {


        List<User> allUsers = userService.getAllUsers();

        String username = loginRequest.getUserName();

        boolean b = allUsers.stream().map(a -> a.getUserName()).anyMatch(bb -> bb.equals(username));

        if (!b){
            return new LoginResponse(false, "未注册","");
        }

        // TODO: 2025.1.11 添加认证相关的内容 

//        User user = userMapper.findUser(loginRequest.getUserName(), loginRequest.getPassword());
//        if (user!= null) {
//
//            return new LoginResponse(true, "登录成功", token);
//        } else {
//            return new LoginResponse(false, "用户名或密码错误", null);
//        }

        ConcurrentMap<String, UserSession> all = userRegistry.getAll();

//        UserSession userSession = new UserSession();

        String token = JWTUtils.generateToken(username);

        User user = new User();
        user.setToken(token);
        user.setUserName(username);

        userOnlineManageServiceI.register(user);
        
        return new LoginResponse(true, "登录成功", token);
    }



}


